package com.minicat.server;

import java.io.*;

/**
 * 封装Response对象，需要依赖于OutputStream
 *
 * 该对象需要提供核心方法，输出html
 */
public class Response {

    private OutputStream outputStream;

    public Response() {
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void output(String content) throws IOException {
        outputStream.write(content.getBytes());
    }

    /**
     * 根据url来获取到静态资源的绝对路径,进一步根据绝对路径读取静态资源文件，最终通过输出流输出
     * @param path
     */
    public void outputHtml(String path) throws IOException {
        String absoluteResourcePath = StaticResourceUtil.getAbsolutePath(path);
        File file = new File(absoluteResourcePath);
        if (file.exists() && file.isFile()){
            //读取静态资源文件，输出静态资源
            StaticResourceUtil.outputStaticResource(new FileInputStream(file),outputStream);
        }else{
            output(HttpProtocolUtil.getHttpHead404());
        }
    }
    public void outputHtml(Request request,Mapper mapper) throws IOException {
        /**
         * 设置媒体类型
         */
        String contentType = "text/html";
        if (request.getUrl().endsWith(".png")){
            contentType = "image/png";
        }else if(request.getUrl().endsWith(".jpg") || request.getUrl().endsWith(".jpeg")){
            contentType = "image/jpeg";
        }else if(request.getUrl().endsWith(".pdf")){
            contentType = "application/pdf";
        }else if (request.getUrl().endsWith(".js")){
            contentType = "application/javascript";
        }else if(request.getUrl().endsWith(".css")){
            contentType = "text/css";
        }
        //先从webapps中查找,找不到就使用默认的
        for (Host host : mapper.getHosts()) {
            if (request.getHost().equalsIgnoreCase(host.getName())){
                File file = new File(host.getAppBase() + "/" + request.getUrl());
                if (file.exists() && file.isFile()){
                    StaticResourceUtil.outputStaticResource(new FileInputStream(file),outputStream,contentType);
                    return;
                }
            }
        }
        outputHtml(request.getUrl());
    }
}
